//
//  MQClassicsAnaViewController.m
//  MQ
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQClassicsAnaViewController.h"
#import "PKRequestManager.h"
#import "MQEmotionModel.h"
#import "MQEmtionCell.h"
#import "MJRefresh.h"
#import <FMDatabase.h>
#import "Reachability.h"
#import "MQFMDBManager.h"
#import "UMSocial.h"
#import "MQReadCollectionModel.h"
@interface MQClassicsAnaViewController ()<UMSocialUIDelegate>
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
//@property (nonatomic, strong) FMDatabase *dataBase;
@end

@implementation MQClassicsAnaViewController
- (NSMutableArray *)dataSourceArr{
    if (_dataSourceArr == nil) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}
- (void)requestData{
  
    [PKRequestManager requestWithType:GET urlString:@"http://ic.snssdk.com/2/essay/zone/category/data/?tag=joke&iid=2539841851&min_time=1421800344&category_id=11&count=30&level=6&ac=wifi&channel=App%2520Store&app_name=joke_essay&aid=7&version_code=3.2.0&device_platform=iphone&os_version=7.1.2&device_type=iPhone%25205C&device_id=3150065001&vid=B18181C6-7BD1-450B-9A8E-534BFFEE7B7B&openudid=71eed7dc309a129c98532aad0ef0ae523a88b0a0&idfa=0B724A85-C91C-40A7-9578-A0E43B92BD77" parDic:nil  finish:^(NSData *data) {
           [[MQFMDBManager shareDataBase] executeUpdate:@"delete from CLASSICS"];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
            
            for (NSDictionary *dic1 in dic[@"data"][@"data"]) {
                MQEmotionModel *model = [[MQEmotionModel alloc] init];
                [model setValuesForKeysWithDictionary:dic1];
                [self.dataSourceArr addObject:model];
                
                // 写入数据
                //                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSString *fav = [NSString stringWithFormat:@"%ld", model.group.favorite_count];
                [[MQFMDBManager shareDataBase] executeUpdate:@"insert into CLASSICS (content, fav) values (?,?)",model.group.content, fav];
                //                });
            }
            
            
                [self.tableView reloadData];
           
            
        
    } error:^(NSError *error) {
        NSLog(@"数据请求错误 %@", [error localizedDescription]);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MQEmtionCell class] forCellReuseIdentifier:@"emtionCell"];
    __weak __typeof(self) weakSelf = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf checkNetConnect];

    }];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf checkNetConnect];
    }];

    [self checkDataBase];
[MQFMDBManager openDataBase:[MQFMDBManager shareDataBase] update:@"CREATE TABLE CLASSICS (content text, fav text)"];
    
      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:@"deleteCollection" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 接收通知后刷新数据
- (void)receiveNotification:(NSNotification *)receiver{
    NSArray *array = receiver.userInfo[@"array"];
    NSLog(@"tongzhi %@", array);
    for (MQEmotionModel *model in self.dataSourceArr) {
        for (MQReadCollectionModel *model1 in array) {
            if ([model.group.content isEqualToString:model1.digest]) {
                model.isCollection = YES;
            }else{
                model.isCollection = NO;
            }
        }
        
    }
    [self.tableView reloadData];
    
}

//#pragma mark 查找数据库
- (void)checkDataBase{
    FMResultSet *resultSet = [[MQFMDBManager shareDataBase] executeQueryWithFormat:@"select * from CLASSICS"];
    while ([resultSet next]) {
        NSString *content = [resultSet stringForColumn:@"content"];
        NSString *fav = [resultSet stringForColumn:@"fav"];
        MQEmotionModel *model = [[MQEmotionModel alloc] init];
        model.group.content = content;
        model.group.favorite_count = [fav integerValue];
        [self.dataSourceArr addObject:model];
        
    }
    [self.tableView reloadData];
    [resultSet close];
}
#pragma mark 判断网络连接
- (BOOL)checkNetConnect{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
        {
            NSLog(@"无网络");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:TITLE_MESSAGE preferredStyle:(UIAlertControllerStyleAlert)];
            
            [self presentViewController:alert animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });
            
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            return NO;
            
        }
            break;
            
        default:{
            [self requestData];
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
        }
            break;
    }
    
    return YES;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSourceArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MQEmtionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"emtionCell" forIndexPath:indexPath];
    MQEmotionModel *model = self.dataSourceArr[indexPath.row];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configureWithModel:model];
    
    [cell.upBtn addTarget:self action:@selector(didClickUpBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.likeBtn addTarget:self action:@selector(dicClickLikeBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.shareBtn addTarget:self action:@selector(didClickShareBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    // 判断点赞
    if (model.isUp == YES) {
        [cell.upBtn setImage:[UIImage imageNamed:@"zan"] forState:(UIControlStateNormal)];
        
    }else{
        [cell.upBtn setImage:[UIImage imageNamed:@"unzan"] forState:(UIControlStateNormal)];
    }
    // 判断收藏
    if (model.isCollection == YES) {
        [cell.likeBtn setImage:[UIImage imageNamed:@"star_faved@2x"] forState:(UIControlStateNormal)];
    }else{
        [cell.likeBtn setImage:[UIImage imageNamed:@"star_unfav@2x"] forState:(UIControlStateNormal)];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MQEmotionModel *model = self.dataSourceArr[indexPath.row];
    return [MQEmtionCell heightForCellWithModel:model];
}

// 点赞
- (void)didClickUpBtn:(UIButton *)sender{
    MQEmtionCell *cell = (MQEmtionCell *)sender.superview.superview.superview;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    MQEmotionModel *model = self.dataSourceArr[index.row];
    
    if (model.isUp == YES) {
        model.group.favorite_count -= 1;
        [sender setImage:[UIImage imageNamed:@"unzan"] forState:(UIControlStateNormal)];
//        sender.selected = NO;
        model.isUp = NO;
        
    }else{
        model.group.favorite_count += 1;
        [cell configureWithModel:model];
        [sender setImage:[UIImage imageNamed:@"zan"] forState:(UIControlStateNormal)];
//        sender.selected = YES;
        model.isUp = YES;
    }
    [self.tableView reloadData];
    
}
// 收藏
- (void)dicClickLikeBtn:(UIButton *)sender{
    MQEmtionCell *cell = (MQEmtionCell *)sender.superview.superview.superview;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
#pragma mark 传出model类
    MQEmotionModel *model = self.dataSourceArr[index.row];
    if (model.isCollection == YES) {
        [sender setImage:[UIImage imageNamed:@"star_unfav@2x"] forState:(UIControlStateNormal)];
//        sender.selected = NO;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已取消收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alert animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
        model.isCollection = NO;
         [[MQFMDBManager shareDataBase] executeUpdate:@"delete from READCOLLECTION where (digest) = (?)",model.group.content];
        
    }else{
        [sender setImage:[UIImage imageNamed:@"star_faved@2x"] forState:(UIControlStateNormal)];
//        sender.selected = YES;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alert animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        });
        model.isCollection = YES;
        [[MQFMDBManager shareDataBase] executeUpdate:@"insert into READCOLLECTION (digest) values (?)",model.group.content];
    }
    [self.tableView reloadData];
    
}
//分享
- (void)didClickShareBtn:(UIButton *)sender{
    NSLog(@"分享");
    MQEmtionCell *cell = (MQEmtionCell *)sender.superview.superview.superview;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    MQEmotionModel *model = self.dataSourceArr[index.row];
#pragma mark 弹出分享菜单
    [UMSocialSnsService presentSnsIconSheetView:self.readVC appKey:@"561b79fde0f55ac7c00016bf"
                                      shareText:model.group.content
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
    
    
}


@end
